<?php

class Product extends AppModel {

    var $name = 'Product';
    var $displayField = 'products_title';
    var $actsAs = array(
        'Uploader.FileValidation' => array(
            'fileName' => array(
                'extension' => array(
                    'value' => array('gif', 'jpg', 'png', 'jpeg'),
                    'error' => 'Filetype incorrect',
                    'on' => 'create'
                ),
                'filesize' => array(
                    'value' => 1048576,
                    'error' => 'Filesize incorrect',
                    'on' => 'create'
                ),
                'required' => array(
                    'value' => false,
                    'error' => 'Select an image',
                    'on' => 'create'
                )
            )
        )
    );
    var $validate = array(
        'products_title' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Enter products title',
            ),
        ),
        'products_price' => array(
            'decimal' => array(
                'rule' => array('numeric'),
                'message' => 'Enter products price.',
            ),
        ),
        'products_quantity' => array(
            'numeric' => array(
                'rule' => array('numeric'),
                'message' => 'Enter products quantity. Should be numeric.',
            ),
        ),
        'handletime_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
                'message' => 'You have to select a handale time.',
            ),
        ),
        'category_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
                'message' => 'You have to select a category.',
            ),
        ),
        'products_description' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Enter products description',
            ),
        )
    );
    var $hasMany = array('ProductImage', 'Note', 'ProductShipping', 'ProductInternationalShipping', 'Salestax');
    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Brand' => array(
            'className' => 'Brand',
            'foreignKey' => 'global_brands',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ), 
        'ProductStyle' => array(
            'className' => 'Brand',
            'foreignKey' => 'global_styles',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'ProductCondition' => array(
            'className' => 'Brand',
            'foreignKey' => 'global_conditions',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Category' => array(
            'className' => 'Category',
            'foreignKey' => 'category_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'HandleTime' => array(
            'class' => 'HandleTime',
            'foreignKey' => 'handletime_id'
        ),
        'Approver' => array(
            'className' => 'User',
            'foreignKey' => 'approved_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ));

    function isowner($pid, $seller_id, $group) {
        if ($group == "1" || $group == "2")
            return true;
        $count = $this->find('count', array('conditions' => array('Product.id' => $pid, 'Product.user_id' => $seller_id)));
        if ($count)
            return true;
        else
            return false;
    }

    function fetchProducts($categoryId, $option) {
        $data = array(
            'conditions' => array('Product.category_id' => $categoryId, 'Product.products_status' => 'Pending'),
            'limit' => 2,
            'order' => array('Product.' . $option . ' DESC'),
            'fields' => array('Product.id', 'Product.products_title', 'Product.products_title', 'User.username')
        );
        return $this->find('all', $data);
    }

    function homePageProducts($category=array(), $option=array('Ending Soon' => array('colName' => 'products_expiredDate', 'order' => 'ASC'), 'Newest' => array('colName' => 'products_createDate', 'order' => 'DESC'), 'Featured' => array('colName' => 'products_createDate', 'order' => 'DESC'))) {
        if (empty($category)) {
            return;
        }
        $i = 0;
        //$allcat=$this->Category->viewAll();        
        $homePageItem = array();
        unset($cat_id);
        $cat_id = array();

        foreach ($category as $categories) {
            unset($cat_id);
            $cat_id = array();
            echo $homePageItem[$i]['category'] = $categories['Category']['category_name'];
            $category = $this->Category->viewAll($categories['Category']['id']);
            echo $i . "=>";
            pr($category);
            $cat_id[] = $categories['Category']['id'];
            foreach ($category as $cat) {
                $cat_id[] = $cat['id'];
            }
            foreach ($option as $key => $value) {
                //'order'=>array('Product.'.$value['colName'].' '.$value['order'].''),
                //$conditions=array('Product.category_id'=>$categories['Category']['id'], 'OR'=>array(array('Product.products_status'=>'Active'),array('Product.products_status'=>'Approved')), 'Product.products_expiredDate >='=>date("Y-m-d H:i:s"));
                switch ($key) {
                    case 'Ending Soon': $conditions = array('Product.category_id' => $cat_id, 'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"));
                        break;
                    case 'Newest':$conditions = array('Product.category_id' => $cat_id, 'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"));
                        break;
                    case 'Featured':$conditions = array('Product.category_id' => $cat_id, 'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"), 'Product.featured' => "Yes");
                        break;
                }

                $data = array(
                    'conditions' => $conditions,
                    'limit' => 4,
                    'order' => array('Product.' . $value['colName'] . ' ' . $value['order'] . ''),
                    'fields' => array('Product.id', 'Product.products_title', 'Product.products_price', 'Product.products_price', 'Product.products_thumbnailImage', 'User.username')
                );
                $homePageItem[$i][$key] = $this->find('all', $data);
            }
            unset($cat_id);
            $cat_id = array();
            $i++;
        }
        return $homePageItem;
    }

    function homePageSlider() {
        $this->recursive = -1;
        $data = array(
            'conditions' => array('OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s")),
            'limit' => 20,
            'order' => ('rand()'),
            'fields' => array('Product.id', 'Product.products_title', 'Product.products_price', 'Product.products_thumbnailImage')
        );
        return $this->find('all', $data);
    }

    function store($allProducts) {
        foreach ($allProducts as $product) {
            $categories[] = $product['Category']['id'];
        }
        $newCategory = array_unique($categories);
        $i = 0;
        foreach ($newCategory as $category) {
            foreach ($allProducts as $pro) {
                if ($pro['Category']['id'] == $category) {
                    $re[$i]['category'] = $pro['Category'];
                    unset($pro['Category']);
                    $re[$i]['product'][] = $pro;
                }
            }
            $i++;
        }
        return $re;
    }

    function commition($proInfo, $buyerId) {
        $price = $proInfo['Product']['products_price'];
        $returnData['hasNegotiation'] = FALSE;
        //check negotiation
        if ($buyerId != 0) {
            App::import('model', 'Negotiation');
            $negotiation = new Negotiation();
            $negotiationData = $negotiation->checkNegotiasion($buyerId, $proInfo['Product']['user_id'], $proInfo['Product']['id']);

            if ($negotiationData) {
                $price = $negotiationData['Negotiation']['last_offer'];
                $returnData['hasNegotiation'] = $price;
            }
        }
        if ($proInfo['Product']['products_commission'] > 0) {
            $newPrice = $this->newPrice($price, $proInfo['Product']['products_commission'], $proInfo['Product']['products_commissionType']);
            $returnData['price'] = $newPrice;
            $returnData['priceChange'] = ($proInfo['Product']['products_price'] - $newPrice) == 0 ? FALSE : TRUE;
        }else
            $returnData['price'] = $price;
        return $returnData;
    }

    function newPrice($price, $commition, $type) {

        if ($type == '$') {
            return ($price - $commition);
        }
        if ($type == '%') {
            return ($price - (($commition * $price) / 100));
        }
    }

    function product_counts($categories) {
        $i = 1;
        foreach ($categories as $category) {
            $categories[$i]['total_product'] = $this->find('count', array('conditions' => array(
                    'Product.category_id' => $category['id'],
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'))));
            $i++;
        }
        return $categories;
    }

    function homePageProducts1($category=array(), $option=array('Ending Soon' => array('colName' => 'products_expiredDate', 'order' => 'ASC'), 'Newest' => array('colName' => 'products_expiredDate', 'order' => 'DESC'), 'Featured' => array('colName' => 'products_createDate', 'order' => 'DESC'))) {
        if (empty($category)) {
            return;
        }
        $i = 0;
        $homePageItem = array();
        foreach ($category as $categories) {
            $cat_id = array();
            $homePageItem[$i]['category'] = $categories['Category']['category_name'];
            $category = $this->Category->allchilds($categories['Category']['id']);
            $j = 0;
            foreach ($option as $key => $value) {
                switch ($key) {
                    case 'Ending Soon': $conditions = array('Product.category_id' => $category, 'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"), 'Product.featured' => "No");
                        $order = array('Product.' . $value['colName'] . ' ' . $value['order'] . '');
                        $limit = 4;
                        break;
                    case 'Newest':$conditions = array('Product.category_id' => $category, 'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"), 'Product.featured' => "No");
                        $order = array('Product.' . $value['colName'] . ' ' . $value['order'] . '');
                        $limit = 4;
                        break;
                    case 'Featured':$conditions = array('Product.category_id' => $category, 'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"), 'Product.featured' => "Yes");
                        $order = 'RAND()';
                        $limit = 4;
                        break;
                }

                $data = array(
                    'conditions' => $conditions,
                    'limit' => $limit,
                    'order' => $order,
                    'fields' => array('Product.id','Product.user_id', 'Product.products_title', 'Product.products_price', 'Product.products_price', 'Product.products_thumbnailImage', 'Product.products_expiredDate', 'User.username')
                );

                $this->unbindModel(array("hasMany" => array('ProductImage', 'Note', 'ProductShipping', 'ProductInternationalShipping', 'Salestax')));
                $homePageItem[$i][$key] = $this->find('all', $data);
            }
            $i++;
        }
        return $homePageItem;
    }

    function brand_menu($type=null) {
        $this->Behaviors->attach('Containable');

        if ($type == 'global_brands') {
            return $this->find('all', array('fields' =>
                        array('Product.id', 'count(Product.' . $type . ') as totalproduct'),
                        'conditions' => array('Product.products_expiredDate >=' => date('Y-m-d H:i:s'), 'OR' => array(array('Product.products_status !=' => 'Disapproved'), array('Product.products_status !=' => 'Pending'))),
                        'contain' => array('Brand.id', 'Brand.brand_description'),
                        'order' => 'totalproduct desc', 'group' => 'Product.' . $type, 'limit' => 5));
        }

        if ($type == 'global_conditions') {
            return $this->find('all', array('fields' =>
                        array('Product.id', 'count(Product.' . $type . ') as totalproduct'),
                        'conditions' => array('Product.products_expiredDate >=' => date('Y-m-d H:i:s'), 'OR' => array(array('Product.products_status !=' => 'Disapproved'), array('Product.products_status !=' => 'Pending'))),
                        'contain' => array('ProductCondition.id', 'ProductCondition.brand_description'),
                        'order' => 'totalproduct desc', 'group' => 'Product.' . $type));
        }

        if ($type == 'global_styles') {
            return $this->find('all', array('fields' =>
                        array('Product.id', 'count(Product.' . $type . ') as totalproduct'),
                        'conditions' => array('Product.products_expiredDate >=' => date('Y-m-d H:i:s'), 'OR' => array(array('Product.products_status !=' => 'Disapproved'), array('Product.products_status !=' => 'Pending'))),
                        'contain' => array('ProductStyle.id', 'ProductStyle.brand_description'),
                        'order' => 'totalproduct desc', 'group' => 'Product.' . $type));
        }
    }

    function productLimit($id=null){
        $total=$this->find('count',array('conditions'=>array('user_id'=>$id)));
        if($total>=10)
            return true;
        else
            return false;
        
    }
}

?>